// pages/bluetooth/index.js
Page({  
  /**
   * 页面的初始数据
   */
  data: {
    list: [],//deviceslist
    switchChecked:false,
    DevicesConnected:[{
      DevicesDisplay: "none",
      name:"",
      deviceId:"",
    }],
  },
  
  //开始或关闭搜索附近的蓝牙设备
  BluetoothSwitchChange:function(e){
    var that = this;      
    if (e.detail.value){
      wx.openBluetoothAdapter({
        success: function (res) {
          console.log(res)
          that.onBluetoothAdapterStateChange();//监听蓝牙适配器状态变化事件
          that.getBluetoothAdapterState();
        },
        fail: function (err) { 
          that.setData({
            'switchChecked': false            
          });              
          console.log(err);
          wx.showModal({
            title: '错误',
            content: '初始化蓝牙失败，请检查是否开启蓝牙设备',
          })  
        }
      })
    }else{
      //关闭蓝牙模块--断开与低功耗蓝牙设备的连接
      wx.closeBluetoothAdapter({        
        success: function (res) {         
          that.setData({
            'list': [],
            'DevicesConnected': [{
              DevicesDisplay: "none",
              name: "",
              deviceId: "",
            }],
          });          
          console.log("关闭蓝牙模块")
          console.log(res)
        }
      })
    }         
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState:function(){
    var that = this;
    wx.getBluetoothAdapterState({
      success: function (res) {
        console.log(res)
        var available = res.available;//蓝牙适配器是否可用
        var discovering = res.discovering;//是否正在搜索设备
        if (!available){
          wx.showModal({
            title: '错误',
            content: '蓝牙适配器状态不可用',
          })
        }
        if (!discovering) {
          that.startBluetoothDevicesDiscovery();     
        }
      }      
    })
  },
  //开始搜寻附近的蓝牙外围设备。注意，该操作比较耗费系统资源，请在搜索并连接到设备后调用 stop 方法停止搜索。
  startBluetoothDevicesDiscovery:function(){
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      // services: [],
      success: function (res) {        
        console.log(res)
        if (res.isDiscovering){
          console.log("开始搜索设备：")
          that.getBluetoothDevices();
        }
      },
      fail: function (err) {
        console.log(err);
        wx.showModal({
          title: '错误',
          content: '搜寻附近的蓝牙外围设备失败',
        })
      }
    })
  },
  //获取所有已发现的蓝牙设备  
  getBluetoothDevices: function () {
    var that = this;
    var length=0;
    var count=0;
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    var deviceslist=[];
    setTimeout(
      function(){
        wx.getBluetoothDevices({
          success: function (res) {
            console.log(res)
            deviceslist = res.devices
            that.setData({
              'list': deviceslist
            });              
          },
        })
        wx.hideLoading()  
      },10000) //搜寻设备10秒
   
  }, 
  //监听蓝牙适配器状态变化事件
  onBluetoothAdapterStateChange: function () {
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(`adapterState changed, now is`, res)   
      var available = res.available;
      if (!available) {
        wx.showModal({
          title: '提示',
          content: '蓝牙已断开',
        }) 
      }               
    })
  }, 
  //连接低功耗蓝牙设备  
  createBLEConnection: function (option) {
    var that = this;        
    console.log(option)    
    wx.createBLEConnection({            
      deviceId: option.currentTarget.dataset.deviceid,
      success: function (res) {
        console.log(res);
        that.setData({
          'DevicesConnected': [{
            DevicesDisplay: "block",
            name: option.currentTarget.dataset.name,
            deviceId: option.currentTarget.dataset.deviceid,            
          }]
        });

        getApp().data.deviceId = option.currentTarget.dataset.deviceid//全局变量赋值

        wx.showToast({
          title: '连接成功',
          icon: 'success',          
        })
      },
      fail: function (err) {
        wx.showModal({
          title: '错误',
          content: '连接失败',
        })
      },
    })
  },  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})